#pragma once
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <http/server.hpp>
#include <string>
#include <memory>
#include <nlohmann/json.hpp>
#include <thread>
#include <atomic>
#include <set>
#include <mutex>

namespace industrial_robot_control {
namespace visualization {

using json = nlohmann::json;
using websocket_server = websocketpp::server<websocketpp::config::asio>;

class WebServer {
public:
    WebServer();
    ~WebServer();
    
    // 启动Web服务器
    bool start(int port = 8080);
    
    // 停止Web服务器
    void stop();
    
    // 处理HTTP和WebSocket请求
    void processRequests();
    
    // 注册数据更新回调
    using DataCallback = std::function<json()>;
    void registerDataCallback(DataCallback callback) { data_callback_ = callback; }
    
    // 发送消息给所有客户端
    void broadcastMessage(const json& message);
    
    bool isRunning() const { return running_; }
    
private:
    int port_;
    std::atomic<bool> running_{false};
    std::unique_ptr<std::thread> server_thread_;
    std::shared_ptr<websocket_server> ws_server_;
    std::shared_ptr<http::server> http_server_;
    
    // 连接的客户端
    std::set<websocketpp::connection_hdl, std::owner_less<websocketpp::connection_hdl>> connections_;
    std::mutex connections_mutex_;
    
    // 数据回调
    DataCallback data_callback_;
    
    // 运行服务器
    void runServer();
    
    // WebSocket处理函数
    void onWebSocketOpen(websocketpp::connection_hdl hdl);
    void onWebSocketClose(websocketpp::connection_hdl hdl);
    void onWebSocketMessage(websocketpp::connection_hdl hdl, websocket_server::message_ptr msg);
    
    // HTTP处理函数
    std::string onHttpRequest(const std::string& path, const std::string& method);
};

} // namespace visualization
} // namespace industrial_robot_control
